package cn.yuanqiao.archive.danganzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.mapper.InitArchiveMapper;
import cn.yuanqiao.archive.danganzhengli.domain.FileAssociation;
import cn.yuanqiao.archive.danganzhengli.mapper.FileAssociationMapper;
import cn.yuanqiao.archive.danganzhengli.service.IFileAssociationService;
import cn.yuanqiao.archive.liyong.service.ListQueryPageService;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 互见号Service业务层处理
 *
 * @author xy
 * @date 2024-10-08
 */
@Service
public class FileAssociationServiceImpl implements IFileAssociationService
{
    @Autowired
    private FileAssociationMapper fileAssociationMapper;
    @Autowired
    private ListQueryPageService listQueryPageService;
    @Autowired
    private InitArchiveMapper initArchiveMapper;
    /**
     * 查询互见号
     *
     * @param id 互见号主键
     * @return 互见号
     */
    @Override
    public FileAssociation selectFileAssociationById(Long id)
    {
        isExistTable();
        return fileAssociationMapper.selectFileAssociationById(id);
    }

    /**
     * 查询互见号列表
     *
     * @param fileAssociation 互见号
     * @return 互见号
     */
    @Override
    public List<FileAssociation> selectFileAssociationList(FileAssociation fileAssociation)
    {
        isExistTable();
        return fileAssociationMapper.selectFileAssociationList(fileAssociation,new TenantYqda().getTableName(), SecurityUtils.getTenantCode());
    }

    /**
     * 新增互见号
     *
     * @param fileAssociation 互见号
     * @return 结果
     */
    @Override
    public int insertFileAssociation(FileAssociation fileAssociation)
    {
        isExistTable();
        Long [] glIds=fileAssociation.getGlIds();
        //查看那些是包含的
        boolean contains = Arrays.asList(glIds).contains(fileAssociation.getDaId());
        if(contains){
            throw new SecurityException("互见号不能关联本档案!");
        }
        //已经添加的不再重复添加
        Long [] newGlIds=fileAssociationMapper.getGlIds(glIds,new FileAssociation().getTableName(),fileAssociation.getDaId());
        ArrayList<Long> list1 = new ArrayList<>(Arrays.asList(glIds));
        ArrayList<Long> list2 = new ArrayList<>(Arrays.asList(newGlIds));
        // 移除list1中与list2相同的元素
        list1.removeAll(list2);
        List<FileAssociation> fileAssociationList=new ArrayList<>();
        for (Long a:list1){
            FileAssociation newFile=new FileAssociation();
            FileAssociation newFile1=new FileAssociation();
            newFile.setDaId(fileAssociation.getDaId());
            newFile.setGlId(a);
            newFile.setType(fileAssociation.getType());
            newFile.setId(cn.yuanqiao.common.utils.SnowflakeIdGenerator.generateId());
            newFile.setCreateId(SecurityUtils.getUserId());
            newFile.setCreateTime(DateUtils.getNowDate());
            fileAssociationList.add(newFile);
            newFile1.setDaId(a);
            newFile1.setGlId(fileAssociation.getDaId());
            newFile1.setType(fileAssociation.getType());
            newFile1.setId(cn.yuanqiao.common.utils.SnowflakeIdGenerator.generateId());
            newFile1.setCreateId(SecurityUtils.getUserId());
            newFile1.setCreateTime(DateUtils.getNowDate());
            fileAssociationList.add(newFile1);

        }

        if(fileAssociationList.size()<=0){
            throw new ServiceException("该数据已关联过！请重新选择数据！");
        }else{
            return fileAssociationMapper.insertFileAssociationList(fileAssociationList,new FileAssociation().getTableName());

        }
    }

    /**
     * 修改互见号
     *
     * @param fileAssociation 互见号
     * @return 结果
     */
    @Override
    public int updateFileAssociation(FileAssociation fileAssociation)
    {
        return fileAssociationMapper.updateFileAssociation(fileAssociation);
    }

    /**
     * 批量删除互见号
     *
     * @param ids 需要删除的互见号主键
     * @return 结果
     */
    @Override
    public int deleteFileAssociationByIds(Long[] ids)
    {
        List<FileAssociation> list=fileAssociationMapper.selectFileAssociationListByIds(ids,new FileAssociation().getTableName());
       List<FileAssociation> list1=new ArrayList<>();
       for(FileAssociation f:list){
           FileAssociation f1=new FileAssociation();
           f1.setDaId(f.getDaId());
           f1.setGlId(f.getGlId());
           list1.add(f1);
           FileAssociation f2=new FileAssociation();
           f2.setDaId(f.getGlId());
           f2.setGlId(f.getDaId());
           list1.add(f2);
       }


        return fileAssociationMapper.deleteFileAssociationByLists(list1,new FileAssociation().getTableName());
    }

    /**
     * 删除互见号信息
     *
     * @param id 互见号主键
     * @return 结果
     */
    @Override
    public int deleteFileAssociationById(Long id)
    {
        return fileAssociationMapper.deleteFileAssociationById(id);
    }

    @Override
    public List<Map<String, Object>> selectDaList(String dh) {
        return fileAssociationMapper.selectDaList(dh,new TenantYqda().getTableName(),SecurityUtils.getTenantCode());
    }

    @Override
    public boolean getRole(Long menuId, Long categoryId) {
        boolean flag=false;
        List<SysRole> roles = SecurityUtils.getLoginUser().getSysUser().getRoles();
        if (roles == null && roles.size() <= 0) {
            return flag;
        }
        String collect = roles.stream().map(m -> String.valueOf(m.getRoleId())).collect(Collectors.joining(","));
        String tenantCode = SecurityUtils.getTenantCode();
        StringBuilder sql = new StringBuilder("");

        if (!SecurityUtils.isDagly()) {
            sql.append(" select count(1) from " + tenantCode + Constants.BIG_TABLE_NAME_TREESROLE);
            sql.append(" tr LEFT JOIN " + tenantCode + Constants.BIG_TABLE_NAME_TREES);
            sql.append(" t ON t.ID = tr.TREE_ID ");
            sql.append(" LEFT JOIN " + tenantCode + Constants.BIG_TABLE_NAME);
            sql.append(" c ON t.CATEGORY_ID = c.ID  where c.IS_DEL = 0 and c.GROUP_ID is not null  ");
            sql.append(" and tr.ROLE_ID IN (" + collect + ")");
            sql.append(" and tr.MENU_ID = '" + menuId + "' and t.CATEGORY_ID='"+categoryId+"' ");
            int count=fileAssociationMapper.getCountRole(sql);
            //判断是否是子节点该档案
            if(count>0){
                //查该档案下面所有子档案的
                flag=true;
            }

        }else{
           flag=true;
        }

      return flag;
    }

    @Override
    public boolean getButton(Long daId) {
        boolean flag=false;
        int count=fileAssociationMapper.getCountDaId(daId,new FileAssociation().getTableName());
        if(count>0){
            flag=true;
        }
        return flag;
    }

    @Override
    public boolean getDocRole(Long daId,Long menuId) {
        boolean flag=false;
        //查看docRole
       // (List<Map<String, Object>> dataList, String menuId, SysUser user, String tenantCode); IS_OPENS SUB_TABLE_NAME CREATE_ID GDCS_ID CREATE_ID
        List<Map<String,Object>> mapList=fileAssociationMapper.selectDocRoleDa(daId,new TenantYqda().getTableName());
        List<Map<String, Object>> dataList= listQueryPageService.authority(mapList,String.valueOf(menuId),SecurityUtils.getLoginUser().getSysUser(),SecurityUtils.getTenantCode());
        if(dataList.size()>0){
            Map<String,Object> da=dataList.get(0);
            if(da.get("is_borrowing_car").toString().equals("0")){
                flag=true;
            }else{
                flag=false;

            }

        }
        return flag;
    }

    public boolean isExistTable(){
        int existTable = initArchiveMapper.isExistTable("" + new FileAssociation().getTableName());
        if(existTable==0){
            fileAssociationMapper.createTables(new FileAssociation().getTableName());
        }
        return true;
    }

}
